package com.campus.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.common.JWTUtil;
import com.campus.common.core.Pager;
import com.campus.common.core.Result;
import com.campus.common.core.TableData;
import com.campus.config.handler.StudentListener;
import com.campus.mapping.ManagerStudentMapping;
import com.campus.model.TManagerStudent;
import com.campus.model.TSysUser;
import com.campus.model.dto.*;
import com.campus.model.vo.StudentExcelVo;
import com.campus.model.vo.StudentSelectVo;
import com.campus.model.vo.StudentUploadVo;
import com.campus.service.IStudentService;
import com.campus.service.ISysUserService;
import com.campus.service.IUserRoleService;
import com.campus.web.vo.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/student")
@Api(tags = "学员管理")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IUserRoleService userRoleService;

    @PostMapping("/add")
    @ApiOperation("新增学员")
    public Result createManagerTeacher(@RequestBody @Validated TManagerStudentCreateDto createDto){
        if (userRoleService.isExist(createDto.getLoginId())){
            return Result.error("该账号已绑定学生或教师");
        }
        return Result.success(studentService.createStudent(createDto));
    }



    @PostMapping("/upload")
    @ApiOperation("批量导入学员（Excel）")
    @ResponseBody
    public ResponseResult<String> excelUpload(MultipartFile file) {
        try {
            System.out.println("file:"+file.getResource());

            EasyExcel.read(file.getInputStream(), StudentUploadVo.class, new StudentListener(studentService,userRoleService)).headRowNumber(1)
                    .sheet().doRead();
            return ResponseResult.ok("文件上传成功");
        } catch (IOException e) {
            return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "文件上传失败");
        }
    }


    /**
     * 导出学员信息到Excel
     */
    @GetMapping("/export")
    @ApiOperation("导出用于导入学员的Excel")
    public void export(HttpServletResponse response) {
        try {
            // 设置响应头，告知浏览器这是一个文件下载请求
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置下载的文件名
            String fileName = URLEncoder.encode("学员信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 获取学员信息表头
            List<StudentUploadVo> studentUploadVos = new ArrayList<>();

            // 使用EasyExcel写入数据到Excel，并应用自定义样式
            EasyExcel.write(response.getOutputStream(), StudentUploadVo.class)
                    .sheet("学员信息")
                    .registerWriteHandler(new CustomCellStyleStrategy()) // 注册自定义样式策略
                    .doWrite(studentUploadVos);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出学员信息到Excel
     */
    @GetMapping("/exportStudents")
    @ApiOperation("导出学员信息到Excel")
    public void exportStudents(HttpServletResponse response) {
        try {
            // 设置响应头，告知浏览器这是一个文件下载请求
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置下载的文件名
            String fileName = URLEncoder.encode("学员信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 获取学员信息列表
            List<TManagerStudent> students = studentService.list();
            List<StudentExcelVo> studentExcelVos = ManagerStudentMapping.INSTANCE.StudentListtoExcel(students);

            // 使用EasyExcel写入数据到Excel，并应用自定义样式
            EasyExcel.write(response.getOutputStream(), StudentExcelVo.class)
                    .sheet("学员信息")
                    .registerWriteHandler(new CustomCellStyleStrategy()) // 注册自定义样式策略
                    .doWrite(studentExcelVos);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定义样式策略
     */
    public static class CustomCellStyleStrategy implements CellWriteHandler {

        @Override
        public void afterCellDispose(CellWriteHandlerContext context) {
            Cell cell = context.getCell();
            Row row = cell.getRow();
            Sheet sheet = context.getWriteSheetHolder().getSheet();

            // 设置行高
            if (row.getRowNum() == 0) { // 只设置标题行的行高
                row.setHeightInPoints(20);
            }

            // 设置列宽
            if (row.getRowNum() == 0) { // 只设置标题行的列宽
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    sheet.setColumnWidth(i, 20 * 270); // 20个字符宽度
                }
            }
        }
    }

    @GetMapping("/list")
    @ApiOperation("学员列表查询")
    public TableData<StudentSelectVo> list(Pager pager, StudentSelectCondition condition) {
        Page<StudentSelectVo> list = studentService.list(pager,condition);
        return TableData.success(list.getRecords(), list.getTotal());
    }

    //查询所有状态为0的学员（需要审核）
    @GetMapping("/listByStatus")
    @ApiOperation("查询所有状态为0的学员（需要审核）")
    public TableData<TManagerStudent> listByStatus(String status) {

        System.out.println(status);
        if (status.equals("1") && status.equals("0")) {
            return TableData.error("状态码错误 只能是已审核(1)或未审核(0)");
        }
        List<TManagerStudent> tManagerStudents = studentService.listByStatus(status);
        return TableData.success(tManagerStudents, tManagerStudents.stream().count());
    }

    //审核学员
    @PutMapping("/checkStudent/{id}")
    @ApiOperation("审核学员")
    public Result<Integer> checkStudent(@PathVariable Long id) {
        System.out.println(id);
        Integer integer = studentService.checkStudent(id);
        return Result.to(integer);
    }

    //批量审核学员
    @PutMapping("/checkStudentBatch")
    @ApiOperation("批量审核学员")
    public Result<Integer> checkStudentBatch(@RequestBody List<Long> ids) {

        Integer integer = studentService.checkStudentBatch(ids);
        return Result.success(integer);
    }
}
